#!/bin/bash
PermRHypertest(){


local tmpd=`mktemp -d tmp.XXXX`;
# echo $tmpd
#local tmpd=tmpd; mkdir -p tmpd;

local Rcmd='
tt=read.table("stdin",header=F);
m=as.matrix(tt[,1:3])
hyper=phyper(tt[,1],tt[,2],1280-tt[,2], tt[,3], lower.tail=F, log.p=F)

for (k in 1:nrow(m)) {
	miR <- c(1:tt[k,2]);
	Z <- numeric();
	pool <- c(1:1288);
		for (i in 1:1000) {
			x <- sample(pool, tt[k,3], replace=F);
			z <- length(x[x<tt[k,2]+1]);
			Z <- c(Z, z);
		}
	PermP=length(Z[Z>tt[k,1]-1])/1000
	tt$hyper=hyper; 
	tt$permP[k]=PermP;
}

write.table(tt,file="OUTPUT",col.name=T,row.name=F,quote=F,sep="\t");
'
# echo $Rcmd

local Rcmd=${Rcmd/OUTPUT/$tmpd\/out};


echo "$Rcmd" > $tmpd/Rcmd

cat $1| R -q --no-save -f $tmpd/Rcmd &> $tmpd/log.txt

if [ -f $tmpd/out ];then
cat $tmpd/out | tr ";" "\t"
fi

local flag=${2:-""};

if [ "$flag" = "log" ]; then
cat $tmpd/log
fi

rm -rf $tmpd
  
}


PermRHypertest $1